import 'dart:convert';

import 'package:client/common/event.dart';
import 'package:client/provider/chat_list_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:client/common/conn.dart';
import 'package:client/common/info_route.dart';
import 'package:client/model/chat_msg_model.dart';
import 'package:client/model/chat_item_model.dart';
import 'package:provider/provider.dart';
import 'package:client/provider/app_provider.dart';
import 'package:client/provider/chat_msg_provider.dart';

class ChatTalk extends StatefulWidget {
  const ChatTalk({super.key});

  @override
  _ChatTalkState createState() => _ChatTalkState();
}

class _ChatTalkState extends State<ChatTalk> {
  final inputController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  ChatItemModel? _curChat;

  @override
  void initState() {
    super.initState();
    ChatListProvider chatList =
        Provider.of<ChatListProvider>(context, listen: false);
    if (chatList.curChat != null) {
      _curChat = chatList.curChat;
    }
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    bus.on(EventBusSet.chatAdd, (arg) {
      setState(() {
        _curChat = arg as ChatItemModel;
      });
    });
    //切换当前聊天用户
    bus.on(EventBusSet.chatChange, (arg) {
      setState(() {
        _curChat = arg as ChatItemModel;
      });
    });

    return Scaffold(
      // appBar: AppBar(
      //   title: Text("aaa"),
      // ),
      body: _buildView(),
    );
  }

  sendInfo() {
    var msg = inputController.text;
    // print(msg);
    var loginUser = AppProvider.getUser();

    var info = {
      "talk_id": _curChat?.talkId,
      "to_uuid": _curChat?.uuid,
      "to_name": _curChat?.name,
      "from_uuid": loginUser.uuid,
      "from_name": loginUser.name,
      "msg": msg,
    };
    var payload = json.encode(info);
    print("talk payload");
    print(payload);
    Conn.send(InfoRoute.reqChatSendMsg, payload);
    inputController.clear();
  }

  Widget _buildView() {
    var loginUser = AppProvider.getUser();

    if (_curChat == null) {
      return Container();
    }

    return Column(children: [
      Row(
        children: [
          Container(
            padding: EdgeInsets.only(left: 20),
            child: Text(_curChat!.name),
          )
        ],
      ),
      Expanded(
          child: Container(
        padding: EdgeInsets.only(left: 20, right: 20),
        child: Consumer<ChatMsgProvider>(
          builder: (context, msgProvider, child) {
            var history = msgProvider.getMsg(_curChat!.talkId);
            // print("history");
            // print(history);

            var listView = ListView.builder(
                itemCount: history.length,
                controller: _scrollController,
                itemBuilder: (context, index) {
                  ChatMsgModel item = history[index];
                  // print(index);
                  // print(history[index]);

                  var position = 1;
                  if (item.uuid == loginUser.uuid) {
                    position = 2;
                  }
                  var msgItem = MsgItem(item.name, item.msg, position);

                  return msgItem;
                });

            Future.delayed(Duration(milliseconds: 100), () {
              _scrollController
                  .jumpTo(_scrollController.position.maxScrollExtent);
            });

            return listView;
          },
        ),
      )),
      RawKeyboardListener(
        focusNode: FocusNode(),
        onKey: (event) {
          // print(event);
          if (event.runtimeType == RawKeyDownEvent &&
              (event.physicalKey == PhysicalKeyboardKey.enter ||
                  event.physicalKey == PhysicalKeyboardKey.numpadEnter)) {
            sendInfo();
          }
        },
        child: Row(children: <Widget>[
          Expanded(
            child: TextField(
              controller: inputController,
              onChanged: (text) {
                if (text.contains('\n')) {
                  inputController.text = text.replaceAll('\n', '');
                  inputController.selection = TextSelection.fromPosition(
                    TextPosition(offset: inputController.text.length),
                  );
                }
              },
              keyboardType: TextInputType.multiline,
              maxLines: 5,
              minLines: 5,
              decoration: const InputDecoration(
                hintText: '输入',
                filled: true,
                fillColor: Colors.white,
                contentPadding:
                    EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                isDense: true,
                border: OutlineInputBorder(
                  gapPadding: 0,
                  borderRadius: BorderRadius.all(Radius.circular(4)),
                  borderSide: BorderSide(
                    width: 1,
                    style: BorderStyle.none,
                  ),
                ),
              ),
            ),
          ),
        ]),
      ),
      TextButton(
          onPressed: () {
            sendInfo();
          },
          child: Text("发送")),
    ]);
  }
}

class MsgItem extends StatelessWidget {
  static int left = 1;
  static int right = 2;

  late int position = 1;
  late String name = "";
  late String content = "";

  MsgItem(this.name, this.content, this.position);

  @override
  Widget build(BuildContext context) {
    var row;
    var p;
    if (this.position == left) {
      row = [
        Text(name),
        Text(":"),
        Text(content),
      ];
      p = MainAxisAlignment.start;
    } else {
      row = [
        Text(content),
        Text(":"),
        Text(name),
      ];
      p = MainAxisAlignment.end;
    }
    // return Expanded(
    //     child: Row(
    //   mainAxisAlignment: p,
    //   children: row,
    // ));

    return Row(
      mainAxisAlignment: p,
      children: row,
    );
  }
}
